﻿using Common.Jwt;
using Common.MefHelp;
using Common.Tools;
using Common.Tools.Model;
using System.Text.Json;

namespace Common.SelectService
{
    public class ClientService
    {
        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <param name="rute">请求路由</param>
        /// <param name="data">请求数据</param>
        /// <param name="contentType">头部</param>
        /// <param name="headers">头部</param>
        /// <returns></returns>
        public static async Task<ResponseResult<TR>> PostAsync<T, TR>(string serviceName, string rute, T data, Dictionary<string, string>? headers = null, string contentType = "application/json")
        {
            var url = await GetUrl(serviceName, rute);
            if (string.IsNullOrWhiteSpace(url))
            {
                return new ResponseResult<TR>() { };
            }
            var d = JsonSerializer.Serialize(data);
            var resposeModel = await RestClientHelper.PostAsync(url, d, GetHeaders(headers), contentType);
            if (resposeModel != null && resposeModel.Code == 200)
            {
                return JsonSerializer.Deserialize<ResponseResult<TR>>(resposeModel.Message);
            }
            LogHelper.Error($"调用接口失败:url={url},data={d}");
            return new ResponseResult<TR>() { Code = resposeModel?.Code ?? 500, Message = resposeModel?.Message ?? "调用接口失败" };

        }

        /// <summary>
        /// 发送Get请求
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <param name="rute">请求路由</param>
        /// <param name="data">数据</param>
        /// <param name="headers">头部</param>
        /// <returns></returns>
        public static async Task<ResponseResult<TR>> GetAsync<TR>(string serviceName, string rute, Dictionary<string, string>? data = null, Dictionary<string, string>? headers = null, string contentType = "text/plain")
        {
            var url = await GetUrl(serviceName, rute);
            if (string.IsNullOrWhiteSpace(url))
            {
                return new ResponseResult<TR>() { };
            }
            var resposeModel = await RestClientHelper.GetAsync(url, data, GetHeaders(headers), contentType);
            if (resposeModel != null && resposeModel.Code == 200)
            {
                return JsonSerializer.Deserialize<ResponseResult<TR>>(resposeModel.Message);
            }
            LogHelper.Error($"调用接口失败:url={url},data={JsonSerializer.Serialize(data ?? new Dictionary<string, string>())}");
            return new ResponseResult<TR>() { Code = resposeModel?.Code ?? 500, Message = resposeModel?.Message ?? "调用接口失败" };
        }

        /// <summary>
        /// post FormData请求
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <param name="rute">请求路由</param>
        /// <param name="strParam">字符串请求参数</param>
        /// <param name="fileParam">文件请求参数</param>
        /// <param name="headers">头部</param>
        /// <returns></returns>
        public static async Task<ResponseResult<TR>> PostFormDataAsync<TR>(string serviceName, string rute, Dictionary<string, string>? strParam = null, Dictionary<string, byte[]>? fileParam = null, Dictionary<string, string>? headers = null)
        {
            var url = await GetUrl(serviceName, rute);
            if (string.IsNullOrWhiteSpace(url))
            {
                return new ResponseResult<TR>() { };
            }
            var resposeModel = await RestClientHelper.PostFormDataAsync(url, strParam, fileParam, GetHeaders(headers));
            if (resposeModel != null && resposeModel.Code == 200)
            {
                return JsonSerializer.Deserialize<ResponseResult<TR>>(resposeModel.Message);
            }
            LogHelper.Error($"调用接口失败:url={url},data={JsonSerializer.Serialize(strParam ?? new Dictionary<string, string>())}");
            return new ResponseResult<TR>() { Code = resposeModel?.Code ?? 500, Message = resposeModel?.Message ?? "调用接口失败" };
        }

        /// <summary>
        /// 获取请求地址
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <param name="rute">路由</param>
        /// <returns></returns>
        private static async Task<string> GetUrl(string serviceName, string rute)
        {
            var url = await Mef.GetService<DiscoverHandle>().SelectService(serviceName);
            var result = string.IsNullOrWhiteSpace(url) ? string.Empty : $"{url}/{rute.TrimStart("/")}";
            return result;
        }
        /// <summary>
        /// 获取头部
        /// </summary>
        /// <param name="headers"></param>
        /// <returns></returns>
        private static Dictionary<string, string> GetHeaders(Dictionary<string, string>? headers = null)
        {
            var token = JwtHelper.GetJwtToken(new JwtUserModel()
            {
                UserName = JwtConfig.Instance.UserName,
                UserId = JwtConfig.Instance.UserId,
                UserType = JwtConfig.Instance.UserType
            });
            headers = headers ?? new Dictionary<string, string>();
            const string key = "Authorization";
            if (headers.ContainsKey(key))
            {
                headers[key] = token;
            }
            else
            {
                headers.TryAdd(key, token);
            }
            return headers;
        }
    }
}
